package com.sunfeng.netty.heima.day01.multithread;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static com.sunfeng.netty.heima.utils.ByteBufferUtil.debugAll;

public class ChannelDemo8 {
    public static void main(String[] args) throws IOException {
        new BossEventLoop().register();
        ;
    }


    @Slf4j
    static class BossEventLoop implements Runnable {
        Selector selector;
        private volatile boolean start = false;
        private WorkerEventLoop[] workers;  //工作线程
        AtomicInteger index = new AtomicInteger();

        // 工作线程只关注链接事件
        public void register() throws IOException {
            // 如果注册过了则不需要重新注册
            if (!start) {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.bind(new InetSocketAddress(8080));
                serverSocketChannel.configureBlocking(false);
                selector = Selector.open();

                serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                workers = initEventLoops();

                new Thread(this, "boss").start();
                log.debug("boss start...");
                start = true;
            }


        }

        // 创建worker 线程
        public WorkerEventLoop[] initEventLoops() {
//        EventLoop[] eventLoops = new EventLoop[Runtime.getRuntime().availableProcessors()];
            WorkerEventLoop[] workerEventLoops = new WorkerEventLoop[2];
            for (int i = 0; i < workerEventLoops.length; i++) {
                workerEventLoops[i] = new WorkerEventLoop(i);
            }
            return workerEventLoops;
        }

        /**
         * 启动boss线程
         */
        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        // 如果是可连接事件
                        if (selectionKey.isReadable()) {
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            log.debug("{} connected", socketChannel.getRemoteAddress());
                            workers[index.getAndIncrement() % workers.length].register(socketChannel);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Slf4j
    static class WorkerEventLoop implements Runnable {

        private Selector worker;
        private Integer index;
        private volatile boolean start = false;

        private final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();

        public WorkerEventLoop(int index) {
            this.index = index;
        }

        public void register(SocketChannel sc) throws IOException {
            // 如果已经启动  则执行注册
            if (!start) {
                worker = Selector.open();
                new Thread(this, "worker-" + index).start();
                start = true;
            }
            tasks.add(() -> {
                try {
                    SelectionKey sckey = sc.register(worker, 0, null);
                    sckey.interestOps(SelectionKey.OP_READ);
                    worker.selectNow();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            worker.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    worker.select();
                    Runnable poll = tasks.poll();
                    if (poll != null) {
                        poll.run();
                    }
                    Iterator<SelectionKey> iterator = worker.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        // 是可读事件吗
                        if (selectionKey.isReadable()) {
                            SocketChannel channel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(128);

                            try {
                                int read = channel.read(byteBuffer);
                                if (read == -1) {
                                    //没有可读消息
                                    selectionKey.cancel();
                                    channel.close();
                                } else {
                                    byteBuffer.flip();
                                    debugAll(byteBuffer);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                selectionKey.cancel();
                                channel.close();
                            }

                        }

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}